package com.ruoyi.messages.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.agent.domain.SysAgent;
import com.ruoyi.agent.mapper.SysAgentMapper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.messages.domain.VO.SysNotifyVO;
import com.ruoyi.store.domain.SysStore;
import com.ruoyi.store.mapper.SysStoreMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.messages.domain.SysNotify;
import com.ruoyi.messages.service.ISysNotifyService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 消息通知Controller
 *
 * @author ruoyi
 * @date 2024-06-26
 */
@RestController
@RequestMapping("/messages/notify")
public class SysNotifyController extends BaseController
{
    @Autowired
    private ISysNotifyService sysNotifyService;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SysAgentMapper agentMapper;
    @Autowired
    private SysStoreMapper storeMapper;
    /**
     * 查询消息通知列表
     */
    @PreAuthorize("@ss.hasPermi('messages:notify:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysNotify sysNotify)
    {
        List<SysNotifyVO> list = sysNotifyService.selectSysNotifyList(sysNotify);
        return getDataTable(list);
    }

    /**
     * 导出消息通知列表
     */
    @PreAuthorize("@ss.hasPermi('messages:notify:export')")
    @Log(title = "消息通知", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysNotify sysNotify)
    {
        List<SysNotifyVO> lists = sysNotifyService.selectSysNotifyList(sysNotify);
        List<SysNotify> list = new ArrayList<>();
        for (SysNotifyVO sysNotifyVO : lists) {
            SysNotify sysNotify1 = new SysNotify();
            BeanUtils.copyProperties(sysNotifyVO,sysNotify1);
            list.add(sysNotify1);
        }
        ExcelUtil<SysNotify> util = new ExcelUtil<SysNotify>(SysNotify.class);
        util.exportExcel(response, list, "消息通知数据");
    }

    /**
     * 获取消息通知详细信息
     */
    @PreAuthorize("@ss.hasPermi('messages:notify:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sysNotifyService.selectSysNotifyById(id));
    }

    /**
     * 新增消息通知
     */
    @PreAuthorize("@ss.hasPermi('messages:notify:add')")
    @Log(title = "消息通知", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysNotify sysNotify)
    {
        return toAjax(sysNotifyService.insertSysNotify(sysNotify));
    }

    /**
     * 修改消息通知
     */
    @PreAuthorize("@ss.hasPermi('messages:notify:edit')")
    @Log(title = "消息通知", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysNotify sysNotify)
    {
        return toAjax(sysNotifyService.updateSysNotify(sysNotify));
    }

    /**
     * 删除消息通知
     */
    @PreAuthorize("@ss.hasPermi('messages:notify:remove')")
    @Log(title = "消息通知", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sysNotifyService.deleteSysNotifyByIds(ids));
    }


    //获取当前用户所在部门的未读消息数量
//    @Anonymous

    @GetMapping("/getUnReadNotifyNum")
    public AjaxResult getUnReadNotifyNum() {
        Long deptId = SecurityUtils.getDeptId();
//        Long deptId=292l;

        //通过查询dept表对应的type得知该用户的地位
        SysDept sysDept = deptMapper.selectDeptById(deptId);
        String type = sysDept.getType();
        if (type=="0"||type.equals("0")) {
            //说明是管理端用户
            String key = "notify_agent_0";
            Set keys = redisTemplate.opsForHash().keys(key);
            int size = keys.size();
            return success(size);
        }
        if (type=="1"||type.equals("1")) {
            //说明是代理商用户
            //根据deptId查对应的代理商id
            List<SysAgent> agents = agentMapper.selectSysAgentByDeptId(deptId);
            if (CollectionUtils.isEmpty(agents)) {
                throw new ServiceException("代理商信息异常");
            }
            Long agentId = agents.get(0).getId();


            String key = "notify_agent_"+agentId;
            Set keys = redisTemplate.opsForHash().keys(key);
            int size = keys.size();
            return success(size);
        }
        if (type=="2"||type.equals("2")) {
            //说明是商铺用户
            List<SysStore> sysStores = storeMapper.selectSysStoreByDeptId(deptId);
            if (CollectionUtils.isEmpty(sysStores)) {
                throw new ServiceException("当前商户异常");
            }

            Long storeId = sysStores.get(0).getId();

            String key = "notify_store_"+storeId;
            Set keys = redisTemplate.opsForHash().keys(key);
            int size = keys.size();
            return success(size);
        }
        else {
            return  error();
        }

    }

    @Anonymous
    @PostMapping("/ReadMessage/{dataId}")
    public AjaxResult ReadMessage(@PathVariable Long dataId) {
        Long deptId = SecurityUtils.getDeptId();
//        Long deptId=100l;

        //通过查询dept表对应的type得知该用户的地位
        SysDept sysDept = deptMapper.selectDeptById(deptId);
        String type = sysDept.getType();
        if (type=="0"||type.equals("0")) {
            //说明是管理端用户
            String key = "notify_agent_0";
             redisTemplate.opsForHash().delete(key,dataId.toString());

            return success();
        }
        if (type=="1"||type.equals("1")) {
            //说明是代理商用户
            String key = "notify_agent_"+deptId;
           redisTemplate.opsForHash().delete(key,dataId.toString());

            return success();
        }
        if (type=="2"||type.equals("2")) {
            //说明是商铺用户
            String key = "notify_store_"+deptId;
            redisTemplate.opsForHash().delete(key,dataId.toString());

            return success();
        }
        else {
            return  error();
        }
    }


}
